import React, { useState, useEffect } from "react";
import { View, StyleSheet, Dimensions, Text, TouchableOpacity, ScrollView, Image, StatusBar } from "react-native";
import { Icon, Input } from "@rneui/themed";
import LinearGradinet from 'react-native-linear-gradient';
import { useSelector, useDispatch } from "react-redux";
import { Shadow } from "react-native-shadow-2";
import { getValue } from '@/utils/deviceStorage'
import Toast from 'react-native-simple-toast'
import ScanModal from '@/components/ScanModal'
import AdvancedOptions from './components/AdvancedOptions'
import GasDetail from './components/GasDetail'
import Loading from "@/components/LoadingModal";
import LockScreenEnter from '@/components/LockScreenEnter'
import { CoinTransparentArray, global } from "@/config/config";
import { getETHBalance, getERC20Balance, transferETH, getETHGasData, getERC20GasData, getETHTxData, getERC20TxData } from '@/utils/transfer'
import CommonContext from '@/utils/createContext'
import { AESdecrypt, getLabel } from "@/utils/util";

const { width, scale } = Dimensions.get('window')
const ratio = width * scale / 1080

const Send = (props) => {

    const dispatch = useDispatch();
    const toAddress = useSelector((state) => state.singleSignReducer.toAddress);
    const [coinType, setCoinType] = useState('')
    const [loadingVisible, setLoadingVisible] = useState(false)
    const [amount, setAmount] = useState('')
    const [gasData, setGasData] = useState({})
    const [gasTime, setGasTime] = useState('Estimated time < 30 seconds')
    const [gasRank, setGasRank] = useState('middle')
    const [upLinkData, setUpLinkData] = useState('')
    const [unSignTx, setUnSignTx] = useState({})
    const [balance, setBalance] = useState('')
    const [selectedWallet, setSelectedWallet] = useState({})
    const [rpcURL, setRPCURL] = useState('')
    const [scanVisible, setScanVisible] = useState(false)
    const [detailVisible, setDetailVisible] = useState(false)
    const [advancedVisible, setAdvancedVisible] = useState(false)
    const [lockVisible, setLockVisible] = useState(false)

    useEffect(() => {
        let params = props.route.params
        let obj = getValue('selectedWallet')
        setSelectedWallet(obj)
        let str
        if (params && params.source === 'main') {
            str = getValue('coinType')
        } else if (params && params.source === 'assets') {
            str = params.coinType
        }
        setCoinType(str)
        getPageData(str, obj)
    }, [])

    const getPageData = async (str, obj) => {
        let RPCNode = getValue('RPCNode')
        setLoadingVisible(true)
        //获取余额
        let rpcurl, num
        switch (str) {
            case 'ETH':
                num = await getETHBalance(obj.address)
                rpcurl = RPCNode
                break;
            case 'USDT':
                num = await getERC20Balance(obj.address)
                rpcurl = RPCNode
                break;
            case 'BSC':
                rpcurl = global.bscrpcurl
                break;
            default:
                rpcurl = RPCNode
                break;
        }
        setBalance(num)
        setRPCURL(rpcurl)
        setLoadingVisible(false)
    }

    const handleGetGasData = () => {
        if (toAddress && parseFloat(amount) >= 0) {
            setLoadingVisible(true)
            setTimeout(() => {
                getGasData()
            }, 100);
        }
    }

    const getGasData = async () => {
        let rpcurl = rpcURL || global.RPCNode
        let fromAddress = selectedWallet.address
        let obj
        //获取矿工费
        switch (coinType) {
            case 'ETH':
                obj = await getETHGasData(rpcurl, fromAddress, toAddress, amount)
                break;
            case 'USDT':
                obj = await getERC20GasData(rpcurl, fromAddress, toAddress, amount)
                break;
            case 'BSC':
                //后续开发
                break;
            default:
                break;
        }
        setGasData(obj)
        setLoadingVisible(false)
    }

    const handlePressExchage = () => {

    }

    const handlePressTransfer = () => {
        if (toAddress && parseFloat(amount) > 0 && gasData.gas) {
            let tx
            //获取签名数据
            switch (coinType) {
                case 'ETH':
                    tx = getETHTxData(gasData, toAddress)
                    break;
                case 'USDT':
                    tx = getERC20TxData(gasData)
                    break;
                case 'BSC':
                    //后续开发
                    break;
                default:
                    break;
            }
            setUnSignTx(tx)
            setLockVisible(true)
        }
    }

    const handleClose = () => {
        setLockVisible(false)
        setTimeout(() => {
            let pwd = getValue('lockPwd')
            let encryptStr = getValue('mnemonicStr')
            let decryptStr = AESdecrypt(pwd.substring(0, 16), pwd.substring(16), encryptStr)
            if (decryptStr) {
                setLoadingVisible(true)
                setTimeout(() => {
                    switch (coinType) {
                        case 'ETH':
                            startTransferETH(decryptStr)
                            break;
                        case 'USDT':
                            startTransferETH(decryptStr)
                            break;
                        default:
                            break;
                    }
                }, 100);
            }
        }, 100);
    }

    const startTransferETH = async (decryptStr) => {
        const result = await transferETH(decryptStr, unSignTx)
        setLoadingVisible(false)
        if (result) {
            Toast.showWithGravity(
                'transfer submit!',
                Toast.SHORT,
                Toast.CENTER)
            props.navigation.navigate('main')
        } else {
            Toast.showWithGravity(
                'transfer error!',
                Toast.SHORT,
                Toast.CENTER)
        }
    }

    const handleReadCode = (result) => {
        const { data } = result;
        if (data && data.length > 0) {
            dispatch({ type: "setToAddress", value: data || '' });
        }
    }

    const handlePressAddressBook = () => {
        props.navigation.navigate('address-book')
    }

    return (
        <View style={styles.container}>
            <StatusBar backgroundColor='#5B6DFD' barStyle='light-content' />
            <View style={styles.headerContent}>
                <View style={{ flexDirection: 'row', width: width, alignItems: 'center', justifyContent: 'space-between', marginTop: 13 * ratio }}>
                    <View style={{ flex: 2 }}>
                        <Icon type="antdesign" name="left" size={16} color='#FFFFFF' style={{ marginLeft: 15 * ratio }}
                            onPress={() => props.navigation.goBack()} />
                    </View>
                    <View style={{ flex: 6, alignItems: 'center' }}>
                        <Text style={styles.title1}>{coinType} Taransfer</Text>
                    </View>
                    <View style={{ flex: 2 }}></View>
                </View>
            </View>
            <ScrollView contentContainerStyle={styles.bodyContent}>
                <View style={{ marginTop: 12 * ratio }}>
                    <Shadow offset={[3, 6]}
                        distance={0} startColor='rgba(0,0,0,0.16)' finalColor='transparent' radius={5}>
                        <TouchableOpacity style={styles.addressContent} onPress={handlePressExchage}>
                            <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                                <LinearGradinet colors={['#4748D9', '#24246D']} start={{ x: 0, y: 0 }}
                                    end={{ x: 0, y: 1 }} style={styles.divider1}>

                                </LinearGradinet>
                                <Text style={{ ...styles.title3, marginLeft: 22 * ratio }}>Payment address</Text>
                            </View>
                            <View style={{ flexDirection: 'row', alignItems: 'center', flex: 1, justifyContent: 'flex-end' }}>
                                <Text ellipsizeMode="middle" numberOfLines={1}
                                    style={{ ...styles.title3, width: 73 * ratio, marginRight: 23 * ratio }}>
                                    {selectedWallet?.address}
                                </Text>
                                <Icon type="antdesign" name="right" size={16} color='#707070' style={{ marginRight: 22 * ratio }} />
                            </View>
                        </TouchableOpacity>
                    </Shadow>
                </View>
                <View style={{ marginTop: 13 * ratio }}>
                    <Shadow offset={[3, 6]}
                        distance={0} startColor='rgba(0,0,0,0.16)' finalColor='transparent' radius={5}>
                        <View style={styles.payContent} onPress={handlePressExchage}>
                            <View style={{ flexDirection: 'row', marginTop: 19 * ratio }}>
                                <View style={{ flex: 5 }}>
                                    <Text style={{ ...styles.title3, marginTop: 9 * ratio, marginLeft: 15 * ratio }}>Receive address</Text>
                                </View>
                                <View style={{ flex: 5, justifyContent: 'flex-end', flexDirection: 'row', alignItems: 'center' }}>
                                    <TouchableOpacity onPress={handlePressAddressBook}>
                                        <Image source={require('@/assets/imgs/dz.png')}
                                            style={{ width: 22 * ratio, height: 22 * ratio, marginRight: 19 * ratio }} />
                                    </TouchableOpacity>
                                    <TouchableOpacity onPress={() => { setScanVisible(true) }}>
                                        <Image source={require('@/assets/imgs/ewm.png')}
                                            style={{ width: 19 * ratio, height: 19 * ratio, marginRight: 14 * ratio }} />
                                    </TouchableOpacity>
                                </View>
                            </View>
                            <View style={{ marginTop: 8 * ratio }}>
                                <Input
                                    containerStyle={styles.textInput1}
                                    onChangeText={text => dispatch({ type: "setToAddress", value: text || '' })}
                                    value={toAddress}
                                    onBlur={handleGetGasData}
                                    placeholder='Please enter the payment address'
                                    placeholderTextColor='#9D9D9D'
                                    inputContainerStyle={{ borderBottomWidth: 0 }}
                                    inputStyle={styles.title4}
                                />
                            </View>
                            <View style={{ marginTop: 22 * ratio, width: '100%', justifyContent: 'flex-start' }}>
                                <Text style={{ ...styles.title3, marginLeft: 15 * ratio }}>Assets</Text>
                            </View>
                            <View style={{ marginTop: 8 * ratio }}>
                                <View style={{ ...styles.textInput1, flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' }}>
                                    <View style={{ flexDirection: 'row', marginLeft: 12 * ratio, alignItems: 'center' }}>
                                        <View style={styles.logoContent}>
                                            <Image source={CoinTransparentArray[coinType]}
                                                style={{ width: 12 * ratio, height: 12 * ratio }} />
                                        </View>
                                        <Text style={{ ...styles.title4, color: '#2A2A2A', marginLeft: 4 * ratio }}>{getLabel(coinType)}</Text>
                                    </View>
                                    <View style={{ flexDirection: 'row', marginRight: 13 * ratio, alignItems: 'flex-end' }}>
                                        <Text style={{ ...styles.title2 }}>{balance && balance.substring(0, 4) || '0.00'}</Text>
                                        <Text style={{ ...styles.title5, color: '#2A2A2A' }}>{balance && balance.substring(4, 9)}</Text>
                                    </View>
                                </View>
                            </View>
                            <View style={{ marginTop: 22 * ratio, width: '100%', flexDirection: 'row', justifyContent: 'space-between' }}>
                                <Text style={{ ...styles.title3, marginLeft: 15 * ratio }}>Amount</Text>
                                <TouchableOpacity style={styles.sendAllContent} onPress={() => setAmount(balance)}>
                                    <Text style={{ ...styles.title6, marginLeft: 15 * ratio }}>Send all</Text>
                                </TouchableOpacity>
                            </View>
                            <View style={{ marginTop: 8 * ratio }}>
                                <Input
                                    containerStyle={styles.textInput1}
                                    onChangeText={text => setAmount(text)}
                                    value={amount}
                                    onBlur={handleGetGasData}
                                    keyboardType='numeric'
                                    inputContainerStyle={{ borderBottomWidth: 0 }}
                                    inputStyle={styles.title4}
                                />
                            </View>
                            <View style={styles.divider2}></View>
                            <View style={{ flex: 1, flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' }}>
                                <View style={{ flex: 5 }}>
                                    <Text style={{ ...styles.title3, marginLeft: 18 * ratio }}>Estimated gas fee</Text>
                                </View>
                                <TouchableOpacity onPress={() => { setDetailVisible(true) }}
                                    style={{ flex: 5, flexDirection: 'row', alignItems: 'center', justifyContent: 'flex-end' }}>
                                    <View style={{ marginRight: 12 * ratio }}>
                                        <Text style={{ ...styles.title4, color: '#2A2A2A', textAlign: 'right' }}>
                                            {gasData && gasData.gas && parseFloat(gasData.gas) && parseFloat(gasData.gas).toFixed(9) || '0.00'} {coinType}
                                        </Text>
                                        <Text style={styles.title5}>{gasTime}</Text>
                                    </View>
                                    <View>
                                        <Icon type="antdesign" name="right" size={12} color='#707070' style={{ marginRight: 13 * ratio }} />
                                    </View>
                                </TouchableOpacity>
                            </View>
                        </View>
                    </Shadow>
                </View>
                <TouchableOpacity onPress={() => { setAdvancedVisible(true) }}
                    style={{ width: width, alignItems: 'flex-end', marginRight: 12 * ratio }}>
                    <Text style={{ ...styles.title4, color: '#5B6DFD', marginTop: 13 * ratio }}>Advanced Options</Text>
                </TouchableOpacity>
                <View style={{ marginTop: 9 * ratio }}>
                    <Shadow offset={[3, 6]}
                        distance={0} startColor='rgba(0,0,0,0.16)' finalColor='transparent' radius={5}>
                        <View style={styles.optionalContent} onPress={handlePressExchage}>
                            <View style={{ flexDirection: 'row', width: '100%', alignItems: 'center', justifyContent: 'space-between', marginTop: 10 * ratio }}>
                                <Text style={{ ...styles.title3, color: '#4F4F4F', marginLeft: 19 * ratio }}>Uplink Data</Text>
                                <View style={{ flexDirection: 'row', marginRight: 15 * ratio }}>
                                    <TouchableOpacity style={styles.button1}>
                                        <Text style={{ ...styles.title5, color: '#4F4F4F' }}>Hexadecimal</Text>
                                    </TouchableOpacity>
                                    <TouchableOpacity style={styles.button2}>
                                        <Text style={{ ...styles.title5, color: '#4F4F4F' }}>Character</Text>
                                    </TouchableOpacity>
                                </View>
                            </View>
                            <View>
                                <Input
                                    multiline={true}
                                    textAlignVertical='top'
                                    containerStyle={styles.textInput2}
                                    onChangeText={text => setUpLinkData(text)}
                                    value={upLinkData}
                                    placeholder='This data will be written into the blockchain, which cannot be deleted or modified after being linked, and can be viewed by anyone'
                                    placeholderTextColor='#898989'
                                    inputContainerStyle={{ borderBottomWidth: 0 }}
                                    inputStyle={{ ...styles.title4, color: '#2A2A2A', paddingTop: 12 * ratio }}
                                />
                            </View>
                        </View>
                    </Shadow>
                </View>
                <View style={styles.buttonContent}>
                    <TouchableOpacity style={styles.button3} onPress={() => { props.navigation.goBack() }}>
                        <Text style={{ ...styles.title4, color: '#2A2A2A' }}>Cancel</Text>
                    </TouchableOpacity>
                    <TouchableOpacity style={styles.button4} onPress={handlePressTransfer}>
                        <Text style={{ ...styles.title4, color: '#FFFFFF' }}>Transfer</Text>
                    </TouchableOpacity>
                </View>
            </ScrollView>
            <CommonContext.Provider value={{ modalVisible: scanVisible, setModalVisible: setScanVisible, handleReadCode }}>
                <ScanModal />
            </CommonContext.Provider>
            {lockVisible && <CommonContext.Provider value={{ modalVisible: lockVisible, setModalVisible: setLockVisible, handleClose }}>
                <LockScreenEnter {...props} />
            </CommonContext.Provider>}
            <CommonContext.Provider value={{
                modalVisible: advancedVisible,
                setModalVisible: setAdvancedVisible,
                gasData, setGasData
            }}>
                <AdvancedOptions />
            </CommonContext.Provider>
            <CommonContext.Provider value={{
                modalVisible: detailVisible,
                setModalVisible: setDetailVisible,
                gasData, setGasData, coinType,
                gasTime, setGasTime,
                gasRank, setGasRank
            }}>
                <GasDetail />
            </CommonContext.Provider>
            {loadingVisible && <Loading visible={loadingVisible} />}
        </View>
    )
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#F5F6FA'
    },
    headerContent: {
        width: width,
        height: 54 * ratio,
        backgroundColor: '#5B6DFD'
    },
    bodyContent: {
        alignItems: 'center'
    },
    addressContent: {
        width: 341 * ratio,
        height: 61 * ratio,
        flexDirection: 'row',
        backgroundColor: '#FFFFFF',
        alignItems: 'center',
        borderRadius: 5
    },
    payContent: {
        width: 341 * ratio,
        height: 376 * ratio,
        backgroundColor: '#FFFFFF',
        alignItems: 'center',
        borderRadius: 5
    },
    sendAllContent: {
        width: 62 * ratio,
        height: 17 * ratio,
        borderColor: '#5B6DFD',
        borderWidth: 1,
        borderRadius: 12,
        justifyContent: 'center',
        marginRight: 14 * ratio
    },
    optionalContent: {
        width: 341 * ratio,
        height: 152 * ratio,
        backgroundColor: '#FFFFFF',
        alignItems: 'center',
        borderRadius: 5
    },
    logoContent: {
        width: 20 * ratio,
        height: 20 * ratio,
        backgroundColor: '#5B6DFD',
        borderRadius: 50,
        justifyContent: 'center',
        alignItems: 'center'
    },
    textInput1: {
        width: 311 * ratio,
        height: 40 * ratio,
        backgroundColor: '#F5F6FA',
        borderRadius: 6
    },
    textInput2: {
        width: 324 * ratio,
        height: 71 * ratio,
        backgroundColor: '#F8F8F8',
        borderRadius: 5,
        marginTop: 13 * ratio
    },
    title1: {
        fontSize: 15,
        fontFamily: 'Microsoft YaHei',
        fontWeight: 'bold',
        color: '#F9F9F9',
        lineHeight: 20
    },
    title2: {
        fontSize: 15,
        fontFamily: 'Microsoft YaHei',
        fontWeight: '400',
        color: '#2A2A2A',
        lineHeight: 20
    },
    title3: {
        fontSize: 14,
        fontFamily: 'Microsoft YaHei',
        fontWeight: '400',
        color: '#262626',
        lineHeight: 19
    },
    title4: {
        fontSize: 12,
        fontFamily: 'Microsoft YaHei',
        fontWeight: '400',
        color: '#898989',
        lineHeight: 15
    },
    title5: {
        fontSize: 10,
        fontFamily: 'Microsoft YaHei',
        fontWeight: '400',
        color: '#898989',
        lineHeight: 13
    },
    title6: {
        fontSize: 9,
        fontFamily: 'Microsoft YaHei',
        fontWeight: '400',
        color: '#5B6DFD',
        lineHeight: 12
    },
    divider1: {
        width: 3 * ratio,
        height: 23 * ratio,
        borderRadius: 2,
        marginLeft: 8 * ratio
    },
    divider2: {
        width: 341 * ratio,
        height: 11 * ratio,
        backgroundColor: '#F5F6FA',
        marginTop: 16 * ratio
    },
    button1: {
        width: 70 * ratio,
        height: 18 * ratio,
        borderWidth: 1,
        borderColor: '#707070',
        justifyContent: 'center',
        alignItems: 'center'
    },
    button2: {
        width: 55 * ratio,
        height: 18 * ratio,
        borderWidth: 1,
        borderLeftWidth: 0,
        borderColor: '#707070',
        justifyContent: 'center',
        alignItems: 'center'
    },
    buttonContent: {
        width: width,
        height: 66 * ratio,
        backgroundColor: "#FFFFFF",
        marginTop: 19 * ratio,
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center'
    },
    button3: {
        width: 140 * ratio,
        height: 39 * ratio,
        borderWidth: 1,
        borderColor: '#707070',
        borderRadius: 4,
        justifyContent: 'center',
        alignItems: 'center'
    },
    button4: {
        width: 140 * ratio,
        height: 39 * ratio,
        backgroundColor: '#5B6DFD',
        borderRadius: 4,
        marginLeft: 28 * ratio,
        justifyContent: 'center',
        alignItems: 'center'
    }
})
export default Send